package com.sgb.kjwl.view.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.mob.MobSDK;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.utils.Constants;
import com.sgb.kjwl.utils.UpdateUtils;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.WebEvent;
import com.swgk.core.event.LoginTokenEvent;
import com.swgk.core.mmkvutil.CacheMarker;
import com.swgk.core.dialog.RoundCornerDialog;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.util.SharedPreferenceUtil;

import org.greenrobot.eventbus.EventBus;

public class WelcomeActivity extends AppActivity {

    private static final String TAG = "WelcomeActivity";
    private boolean customSplash = false;
    private static boolean firstEnter = true; // 是否首次进入

    @Override
    protected boolean statusBarDark() {
        return true;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        if (!customSplash) {
            showMainActivity();
        }
    }

    @Override
    protected void initView() {
        immersionBar.transparentNavigationBar().init();
        initCleanData();
        if (msavedInstanceState != null) {
            setIntent(new Intent()); // 从堆栈恢复，不再重复解析之前的intent
        }

        if (!firstEnter) {
            showMainActivity(); // APP进程还在，Activity被重新调度起来
        } else {
            customSplash = true; // APP进程重新起来
        }

    }

    @Override
    protected void init() {
        super.init();
        if (firstEnter) {
            firstEnter = false;
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    customSplash = false;
                    showMainActivity();
                }
            };
            if (customSplash) {
                new Handler().postDelayed(runnable, 100);
            } else {
                runnable.run();
            }
        }
    }

    /**
     * 当app是重新安装时，清除缓存数据
     */
    private void initCleanData() {
        int localVersion = UpdateUtils.getInstance().getLocalVersion(this);
        int oldVersion = MkvUtils.get().getInt(MkvUtils.CommomData, CacheMarker.OldVersionCode, 0);

        if (oldVersion == 0) {
            MkvUtils.get().clear();
        }
        if (oldVersion != localVersion) {
            //清除缓存数据
            MkvUtils.get().clear(MkvUtils.CacheModular);
            MkvUtils.get().putInt(MkvUtils.CommomData, CacheMarker.OldVersionCode, localVersion);
            MkvUtils.get().clear(MkvUtils.CacheUserCenterMenu);//清除用户中心菜单
            if (oldVersion <= 202){ // 保证之前老IM的用户升级新IM版本时，能正常升级。
                cleanTokenInfo();
            }
        }

        //处理v3.0.8缓存标题问题
        String string = MkvUtils.get().getString(MkvUtils.CommomData, CacheMarker.HomePageTitleFix, "");
        if (TextUtils.isEmpty(string) || string.equals("feikongFour")) {
            MkvUtils.get().clear(MkvUtils.CacheModular);
            MkvUtils.get().clear(MkvUtils.CommomData);
            MkvUtils.get().putString(MkvUtils.CommomData, CacheMarker.HomePageTitleFix, "feikongFive");
            MkvUtils.get().putInt(MkvUtils.CommomData, CacheMarker.OldVersionCode, localVersion);
        }

    }

    /**
     * 清除登录信息
     */
    private void cleanTokenInfo(){
        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_TOKEN, "");
        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_PC_TOKEN, "");
        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.resourceAPPToken, "");
        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.resourcePCToken, "");
        EventBus.getDefault().postSticky(new LoginTokenEvent());
    }


    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(0, 0);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.clear();
    }

    private void showMainActivity() {
        //判断是否同意过授权，弹出隐私权限询问弹框
        boolean aBoolean = MkvUtils.get().getBoolean(MkvUtils.CommomData, CacheMarker.PrivacyAgreement, false);
        if (aBoolean) {
            showMainActivity(null);
        } else {
            showDialog();
        }
    }

    /**
     * 隐私政策弹框
     */
    private void showDialog() {
        View view = View.inflate(getActivity(), R.layout.dialog_privacy_agreement, null);
        final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(WelcomeActivity.this, 0, 0, view, R.style.RoundCornerDialog);
        roundCornerDialog.show();
        roundCornerDialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
        roundCornerDialog.setCancelable(false);

        TextView tvService = view.findViewById(R.id.tv_service);
        TextView tvAgreement = view.findViewById(R.id.tv_agreement);
        TextView tvLogoutConfirm = view.findViewById(R.id.tv_logout_confirm);
        TextView tvLogoutCancel = view.findViewById(R.id.tv_logout_cancel);

        tvService.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                EventBus.getDefault().postSticky(WebEvent.make(EventConstant.EVENT_WEBVIEW, Constants.LICENCE_URL));
                WebActivity.start(WelcomeActivity.this);
            }
        });

        tvAgreement.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                EventBus.getDefault().postSticky(WebEvent.make(EventConstant.EVENT_WEBVIEW, Constants.POLICY_URL));
                WebActivity.start(WelcomeActivity.this);
            }
        });

        //确定
        tvLogoutConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (roundCornerDialog != null && roundCornerDialog.isShowing()) {
                    roundCornerDialog.dismiss();
                    MkvUtils.get().putBoolean(MkvUtils.CommomData, CacheMarker.PrivacyAgreement, true);
                    //给MoBSdk回传用户隐私授权结果
                    MobSDK.submitPolicyGrantResult(true, null);
                    showMainActivity(null);
                }
            }
        });
        //取消
        tvLogoutCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (roundCornerDialog != null && roundCornerDialog.isShowing()) {
                    roundCornerDialog.dismiss();
                    System.exit(0);
                }
            }
        });
    }

    private void showMainActivity(Intent intent) {
        boolean aBoolean = MkvUtils.get().getBoolean(MkvUtils.CommomData, CacheMarker.CacheForTheFirstTime, true);
        if (aBoolean) {
            PreferredChoiceActivity.start(WelcomeActivity.this, true);
            finish();
        } else {
            MainActivity.start(WelcomeActivity.this, intent);
            finish();
        }
    }
}
